package cn.yto.wdgj.wdgjgptdigitaltool.service.impl;

import cn.yto.response.DataResult;
import cn.yto.wdgj.wdgjgptdigitaltool.mapper.gpt.CaseImportMapper;
import cn.yto.wdgj.wdgjgptdigitaltool.service.CaseImportService;
import com.alibaba.excel.EasyExcel;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class CaseImportServiceImpl implements CaseImportService {
    @Autowired
    private CaseImportMapper caseImportMapper;

    @Override
    public String importExcel(MultipartFile file) {
        try {
            List<Map<Integer, String>> dataList = EasyExcel.read(file.getInputStream())
                    .sheet()
                    .headRowNumber(1)
                    .doReadSync();

            for (Map<Integer, String> rowData : dataList) {
                processRow(rowData);
            }
            return "导入成功，共导入" + dataList.size() + "条数据";
        } catch (IOException e) {
            throw new RuntimeException("文件读取失败", e);
        }
    }

    private void processRow(Map<Integer, String> rowData) {
        String intentName = rowData.get(0);
        String tag = rowData.get(1);
        String matcherContent = rowData.get(2);

        validateData(intentName, tag, matcherContent);

        try {
            caseImportMapper.insertCase(intentName, tag, matcherContent);
        } catch (Exception e) {
            throw new RuntimeException("数据库插入失败: " + e.getMessage());
        }
    }

    private void validateData(String intentName, String tag, String matcherContent) {
        if (StringUtils.isBlank(intentName)) {
            throw new IllegalArgumentException("意图名称不能为空");
        }
        if (intentName.length() > 100) {
            throw new IllegalArgumentException("意图名称长度超过限制");
        }
        if (StringUtils.isBlank(tag)) {
            throw new IllegalArgumentException("tag不能为空");
        }
        if (StringUtils.isBlank(matcherContent)) {
            throw new IllegalArgumentException("用例内容不能为空");
        }
        // 其他字段校验逻辑...
    }



}
